package com.eastmelon.javase;

/**
 * @ClassName: ThreadCommunication
 * @Description: 子线程循环10次，主线程循环100次，共循环50次
 * @author eastmelon
 */
public class ThreadCommunication {
	public static void main(String[] args) {
		final Run run = new Run();
		new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 50; i++) {
					run.sub();
				}
			}
		}).start();
		for (int i = 0; i < 50; i++) {
			run.main();
		}
	}
}

class Run {// 将两个循环的方法写在一个类中，保证互斥锁一致另一个思路是使用ThreadCommunication.class对象保证同步锁一致
	boolean sub = true;
	public synchronized void main() {
		while(sub) {
			try {
				this.wait();
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
			for (int i = 0; i < 100; i++) {
				System.out.println("main" + i);
			}
			sub=true;
			this.notify();
			
	}

	public synchronized void sub() {
		while(!sub)
		{
			try {
				this.wait();
			}
			catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int i = 0; i < 10; i++) {
			System.out.println("sub" + i);
		}
		sub = false;
		this.notify();//唤醒阻塞的线程
	}
}
